<?php

use Illuminate\Database\Seeder;
use App\Models\Company;
use App\Models\Area;
use App\Models\Category;
use App\Models\User;

class CompaniesTableSeeder extends Seeder
{
    public function run()
    {
        // 所有用户 ID 数组，如：[1,2,3,4]
        $user_ids = User::all()->pluck('id')->toArray();

        // 所有分类 ID 数组，如：[1,2,3,4]
        $category_ids = Category::all()->pluck('id')->toArray();

        // 所有区域ID 数组，如：[1,2,3,4]
        $area_ids = Area::all()->pluck('id')->toArray();

        // 获取 Faker 实例
        $faker = app(Faker\Generator::class);


        $companies = factory(Company::class)
                        ->times(100)
                        ->make()
                        ->each(function ($company, $index)
                            use ($area_ids, $faker)
        {
            // 从区域 ID 数组中随机取出一个并赋值
            $company->area_id = $faker->randomElement($area_ids);

        });

        // 将数据集合转换为数组，并插入到数据库中
        Company::insert($companies->toArray());

        // 所有商家
        $companies = Company::all();

        $companies->each(function ($company, $index) use ($user_ids, $category_ids, $faker) {
            $company->users()->attach($faker->randomElement($user_ids));
            $company->categories()->attach($faker->randomElement($category_ids));
        });

    }

}

